package com.imporven.sell.service.impl;

import com.imporven.sell.domain.ProductInfo;
import com.imporven.sell.dto.CartDTO;
import com.imporven.sell.enums.ProductStatusEnum;
import com.imporven.sell.enums.ResultEnum;
import com.imporven.sell.exception.SellException;
import com.imporven.sell.repository.ProductInfoRepository;
import com.imporven.sell.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author imporven
 * @version 1.0.0
 * @date 2018-7-8 21:17
 * 商品信息服务类实现
 */
@Service
public class ProductServiceImp implements ProductService {

    @Autowired
    ProductInfoRepository productInfoRepository;

    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> cartDTOList) {
        for (CartDTO cart: cartDTOList) {
            ProductInfo product = productInfoRepository.findById(cart.getProductId())
                                    .orElseThrow(new SellException(ResultEnum.PRODUCT_NOT_EXIST));

            int result = product.getProductStock() - cart.getProductNum();
            if(result < 0){
                throw new SellException(ResultEnum.PRODUCT_STACK_NOT_ENOUGH);
            }

            product.setProductStock(result);

            productInfoRepository.save(product);
        }
    }
}
